# server/server.py
from flask import Flask, jsonify, request
from com.service.file_service import FileService
from com.dao.account_dao import AccountDao
import pymysql
import configparser
import jwt
import datetime

app = Flask(__name__)
file_service = FileService()
account_dao = AccountDao()

SECRET_KEY = "Denmouv"

# 数据库连接配置
def get_db_connection():
    config = configparser.ConfigParser()
    config.read('config.ini') 
    db_config = config['db']
    
    return pymysql.connect(
        host=db_config['host'],
        port=int(db_config['port']),
        user=db_config['user'],
        password=db_config['password'],
        database=db_config['database'],
        charset=db_config['charset']
    )

@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    userid = data.get('account_id')
    password = data.get('password')

    connection = get_db_connection()
    try:
        with connection.cursor() as cursor:
            sql = "SELECT userid, email, name, addr, city, country, phone, points FROM accounts WHERE userid=%s AND password=%s"
            cursor.execute(sql, (userid, password))
            user = cursor.fetchone()

            if user:
                token = jwt.encode({
                    "user_id": user[0],
                    "exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1)
                }, SECRET_KEY, algorithm="HS256")

                response = {
                    "status": "success",
                    "user_data": {
                        "userid": user[0],
                        "email": user[1],
                        "name": user[2],
                        "addr": user[3],
                        "city": user[4],
                        "country": user[5],
                        "phone": user[6],
                        "points": user[7]
                    },
                    "token": token,
                    "message": "登录成功"
                }
            else:
                response = {
                    "status": "failure",
                    "message": "用户名或密码错误"
                }
    finally:
        connection.close()

    return jsonify(response)

@app.route('/files', methods=['GET'])
def get_all_files():
    """获取所有文件信息"""
    data = file_service.get_all_files()
    return jsonify(data)

@app.route('/files/<category>', methods=['GET'])
def get_files_by_category(category):
    """按类别获取文件信息"""
    data = file_service.get_files_by_category(category)
    return jsonify(data)

@app.route('/file/<file_id>', methods=['GET'])
def get_file_by_id(file_id):
    """按文件ID获取文件信息"""
    data = file_service.get_file_by_id(file_id)
    return jsonify(data)

if __name__ == '__main__':
    from com.config import SERVER_CONFIG
    app.run(host=SERVER_CONFIG['host'], port=SERVER_CONFIG['port'], debug=SERVER_CONFIG['debug'])